using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
//using E = Excel;
using System.Reflection;
using Dimok.Data.Database;
using Dimok.Exceptions;
using Img = Dimok.Images;

/*
Name:String,Type:String - Type:adVarChar,Attrs:104,Size:50
Name:Integer,Type:Int32 - Type:adInteger,Attrs:120,Size:4
Name:Date,Type:DateTime - Type:adDBTimeStamp,Attrs:120,Size:16
Name:Decimal,Type:Decimal - Type:adNumeric,Attrs:120,Size:19
Name:Byte,Type:Byte - Type:adUnsignedTinyInt,Attrs:120,Size:1
Name:Boolean,Type:Boolean - Type:adBoolean,Attrs:120,Size:2
Name:Text,Type:String - Type:adLongVarChar,Attrs:232,Size:2147483647
Name:Image,Type:Byte[] - Type:adLongVarBinary,Attrs:232,Size:2147483647
Name:SmallMone,Type:Decimal - Type:adCurrency,Attrs:120,Size:8
Name:Money,Type:Decimal - Type:adCurrency,Attrs:120,Size:8
Name:Float,Type:Double - Type:adDouble,Attrs:120,Size:8
 
*/
namespace ImageToDisk{
	public class ImageTree{
		public ImageTree(){}
		public static void MakeImageTree(string path,MainForm mainForm){
			//object m = Missing.Value;
			string conn = ConfigurationSettings.AppSettings["conn"];
			string connADO = ConfigurationSettings.AppSettings["connADO"];
			string connImages = ConfigurationSettings.AppSettings["connImages"];
			StreamReader sr = new StreamReader(path);
			path = Path.Combine(Path.GetDirectoryName(path),"Images for "+Path.GetFileNameWithoutExtension(path));
			//E.ApplicationClass excel = new E.ApplicationClass();
			//E.Workbook wb = null;
			//wb = (E.Workbook)excel.Workbooks.Open((path,m,m,m,m,m,m,m,m,m,m,m,m);
			//E.Worksheet wsh = (E.Worksheet)wb.Worksheets[1];
			//Excel.Range applID = wsh.get_Range(column+"2",m);
			int count = 0;
			while(sr.Peek()>=0) {
				string applID = sr.ReadLine().Trim();
				if(applID != "" && int.Parse(applID) != 0) {
					count++;
					DataSet dsAppl = SQLHelperEx.ExecuteDatasetEx(conn,"SELECT FirstName + ' ' + LastName + ' (' + SSN + ')' AS Name FROM  t_Applicants WHERE ApplicantID = @ApplID",applID);
					string sqlImageTypes = 
						@"SELECT t_Image.ImageTypeID AS FolderID, t_ImageType.ImageType AS FolderName
	FROM  t_Image INNER JOIN t_ImageType ON t_Image.ImageTypeID = t_ImageType.ID
	WHERE (NOT (t_Image.ImageTypeID IN(SELECT value FROM   dbo.registryvalues('FSBImageException') registryvalues))) AND
				(t_Image.ApplicantID = @ApplID)
	ORDER BY t_Image.ApplicantID DESC, t_Image.ImageTypeID";
					DataRowCollection drFolderIDs = SQLHelperEx.ExecuteDatasetEx(connImages,sqlImageTypes,applID).Tables[0].Rows;
					string dir = Path.Combine(path,dsAppl.Tables[0].Rows[0]["Name"].ToString());
					Directory.CreateDirectory(dir);
					foreach(DataRow row in drFolderIDs){
						string folderPath = Path.Combine(dir,Regex.Replace(row["FolderName"]+"",@"[^\w]","_")+".PDF");
						mainForm.stBar.Text = folderPath;
						System.Windows.Forms.Application.DoEvents();
						if( File.Exists(folderPath) && new FileInfo(folderPath).Length > 0 )continue;
						try{
							//Img.Pages.ImagePageCount(connImages,int.Parse(applID),int.Parse(row["FolderID"].ToString()));
							SaveBytes(Img.Pages.ImageFolder(connImages,int.Parse(applID),int.Parse(row["FolderID"].ToString()),Img.PageTypes.PDF),folderPath);
						}catch(Exception exc){
							mainForm.txtError.Text += "***** Folder:"+folderPath+Environment.NewLine+ClientException.GetExceptions(exc);
							System.Windows.Forms.Application.DoEvents();
						}
					}

					//					DataSet dsImages = SQLHelperEx.ExecuteDataset(conn,"x_doug_ImageInfo",int.Parse(applID.Text.ToString()));
					//					DataRow rowAppl = dsImages.Tables[0].Rows[0];
					//					DataRowCollection rowsImages = dsImages.Tables[1].Rows;
					//					string dir = Path.Combine(path,rowAppl["Name"]+"");
					//					Directory.CreateDirectory(dir);
					//					stBar.Text = dir;
					//					foreach( DataRow row in rowsImages )
					//						SaveBytes((byte[])row["Data"],Path.Combine(dir,Regex.Replace(row["ImageType"]+"",@"[^\w]","_")+".tif"));
					//					applID = applID.get_Offset(1,0);
				}
				//if(wb != null )wb.Close(false,m,m);
				//excel.Quit();
			}
			mainForm.stBar.Text = "Done with "+path;
		}
		private static void SaveBytes(byte[] bytes,string fileName){
			if( bytes == null )return;
			fileName = fileName.Replace("..",".");
			FileStream fs = new FileStream(fileName,FileMode.Create);
			fs.Write(bytes,0,bytes.Length);
			fs.Close();
		}
	}
}
